﻿using Anley.DomainDrivenDesign.Contract.Configuration;

namespace Anley.DomainDrivenDesign.Contract.Helper;

/// <summary>
/// 邮件帮助类
/// </summary>
public class MailHelper
    : IMailHelper
{
    private readonly SmtpConfiguration _smtpConfiguration;

    public MailHelper(
        IOptionsMonitor<SmtpConfiguration> smtpConfiguration)
    {
        _smtpConfiguration = smtpConfiguration.CurrentValue;
    }

    // 发送邮件
    public async Task SendEmailSync(
        Tuple<string, string> from,
        List<Tuple<string, string>> to,
        string subject,
        string body,
        bool isBodyHtml = false,
        List<Tuple<string, string>>? cc = null)
    {
        // 实例化邮件消息
        using var mailMessage = new MimeMessage();
        mailMessage.From.Add(new MailboxAddress(from.Item1, from.Item2));
        foreach (var item in to)
            mailMessage.To.Add(new MailboxAddress(item.Item1, item.Item2));
        if (cc?.Count > 0)
            foreach (var item in cc)
                mailMessage.Cc.Add(new MailboxAddress(item.Item1, item.Item2));
        mailMessage.Subject = subject;
        mailMessage.Body = new TextPart("plain")
        {
            Text = body
        };
        // 实例化SMTP客户端
        using var smtpClient = new SmtpClient();
        await smtpClient.ConnectAsync(_smtpConfiguration.Host, _smtpConfiguration.Port, _smtpConfiguration.EnableSsl);
        await smtpClient.AuthenticateAsync(_smtpConfiguration.UserName, _smtpConfiguration.Password);
        // 发送邮件
        await smtpClient.SendAsync(mailMessage);
        // 释放资源
        await smtpClient.DisconnectAsync(true);
    }
}